package com.zd.controller;

import com.zd.domain.Course;
import com.zd.domain.GoodState;
import com.zd.domain.Order;
import com.zd.domain.Result;
import com.zd.service.course.CourseService;
import com.zd.service.goodstate.GoodStateService;
import com.zd.service.order.OrderService;
import com.zd.utils.CourseIdGeneration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodStateService goodStateService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 根据用户id查询用户的全部订单
     *
     * @param userId
     * @return
     */
    @CrossOrigin
    @GetMapping("/myOrder")
    public Result<List<Order>> findOrdersByUserId(@RequestParam("userId") int userId) {

        String findKey = userId + "orders";
//        redisTemplate.delete(findKey);
        List<Order> orders = (List<Order>) redisTemplate.boundValueOps(findKey).get();

        Result<List<Order>> result = new Result<>();

        if (orders == null) {

            List<Order> ordersByUserId = orderService.findOrdersByUserId(userId);

            if (ordersByUserId == null) {
                result.setCode(411);
                result.setMsg("暂无订单，快去下单吧~~");
            } else {
                result.setCode(200);
                result.setMsg("查询成功");
                result.setData(ordersByUserId);
//                redisTemplate.boundValueOps(findKey).set(ordersByUserId,1, TimeUnit.MINUTES);
            }
        } else {
            result.setCode(200);
            result.setMsg("查询成功");
            result.setData(orders);
        }
        return result;
    }

    /**
     * 修改订单状态(未支付-->已支付)，同时修改用户和课程之间的关系
     *
     * @param orderNo
     * @return
     */
    @CrossOrigin
    @GetMapping("/updateState")
    public Result<Course> updateOrderState(@RequestParam("orderNo") int orderNo,
                                           @RequestParam("userId") int userId,
                                           @RequestParam("goodId") int goodId) {

        //修改订单状态
        int influenceRows = orderService.updateOrderState(orderNo);
        Result<Course> result = new Result<>();
        if (influenceRows == 0) {
            //influenceRows == 0说明修改失败
            result.setMsg("支付失败");
            result.setCode(411);
        } else {
            //修改用户与课程之间的关系
            GoodState goodState;
            //查找有没有
            while (true) {
                goodState = goodStateService.findGoodState(userId, goodId);
                if (goodState == null) {
                    //没有找到的话创建一个
                    goodStateService.saveGoodState(userId, goodId);
                } else {
                    break;
                }
            }
            int influenceRows1 = goodStateService.updateGoodIsBuy(goodState.getUserId(), goodState.getGoodId());

            if (influenceRows1 == 0) {
                result.setMsg("支付失败");
                result.setCode(411);

            } else {
                result.setMsg("支付成功");
                result.setCode(200);
                //支付成功后，将课程全部内容返回给前端
                Course course = courseService.findCourseById(goodId);
                result.setData(course);
            }

        }
        return result;
    }

    /**
     * 修改订单状态(等待支付-->未支付)，同时修改用户和课程之间的关系
     *
     * @param orderNo
     * @return
     */
    @CrossOrigin
    @GetMapping("/updateOrderNoPay")
    public Result<Course> updateOrderNoPay(@RequestParam("orderNo") int orderNo) {
        //修改订单状态
        int influenceRows = orderService.updateOrderNoPay(orderNo);
        Result<Course> result = new Result<>();
        if (influenceRows == 0) {
            result.setMsg("修改成功");
            result.setCode(200);
        } else {
            result.setMsg("修改失败");
            result.setCode(411);
        }
        return result;
    }

    /**
     * 根据订单号查找订单
     *
     * @param orderNo
     * @return
     */
    @CrossOrigin
    @GetMapping("/findOrder")
    public Result<Order> findOrderByOrderNo(@RequestParam("orderNo") int orderNo) {
        Order orderByOrderNo = orderService.findOrderByOrderNo(orderNo);
        Result<Order> result = new Result<>();
        if (orderByOrderNo != null) {
            result.setCode(200);
            result.setMsg("查找成功");
            result.setData(orderByOrderNo);
        } else {
            result.setCode(411);
            result.setMsg("查无此数据");
        }

        return result;
    }

    /**
     * 新增订单
     *
     * @param userId
     * @param goodId
     * @return
     */
    @CrossOrigin
    @GetMapping("saveOrder")
    public Result saveOrder(@RequestParam("userId") int userId,
                            @RequestParam("goodId") int goodId) {
        //查找这个课程，找出价格
        Course course = courseService.findCourseById(goodId);
        //生成课程号
        int orderNo = CourseIdGeneration.generateRandom9DigitNumber();
        //封装
        Order addOrder = new Order();
        addOrder.setOrderNo(orderNo);
        addOrder.setUserId(userId);
        addOrder.setGoodId(goodId);
        addOrder.setCourseCPrice(course.getCourseCPrice());
        orderService.saveOrder(addOrder);
        Order order = orderService.findOrderByOrderNo(orderNo);

        Result result = new Result();

        if (order != null) {
            result.setCode(200);
            result.setData(order);
            result.setMsg("订单创建成功~！");
        } else {
            result.setCode(411);
            result.setMsg("订单创建失败！~");
        }
        if (result.getCode() == 200) {
            //再创建用户和课程关系订单（先去查找有没有，没有的话在创建）
            GoodState goodState = goodStateService.findGoodState(userId, goodId);

            if (goodState == null) {
                goodStateService.saveGoodState(userId, goodId);
            }
        }
        return result;
    }

    @GetMapping("findPayState")
    public Result<Order> findPayState(@RequestParam("userId") int userId,
                                      @RequestParam("goodId") int goodId) {

        Result<Order> result = new Result<>();
        Order order = orderService.findPayState(userId, goodId);
        if (order != null) {
            result.setCode(200);
            result.setData(order);
            result.setMsg("查找成功");
        } else {
            result.setCode(411);
            result.setMsg("未找到");
        }
        return result;
    }
}
